'use strict';
const fs = require('fs'); //文件模块
const path = require('path'); //系统路径模块
const { pipeline } = require('stream');
const { exec } = require('child_process');
const compressing = require('compressing');
import config from './config';

const pkg = `${config.name}_${config.version}`;

// vue-cli-service 的 --name 选项会决定 script.onload 后组件在 window 对象挂载的名称
const cmd = `node --max_old_space_size=4096 node_modules/@vue/cli-service/bin/vue-cli-service.js build --target lib --dest builtPkg --report --name ${pkg} src/CIF/ComponentPackager/entry.js `;

exec(cmd, function (error, stdout, stderr) {
	console.log('CIF.CP.buildPkg:exec stdout ', stdout);

	if (error !== null) {
		console.log('CIF.CP.buildPkg:exec error ', error);
		console.log('CIF.CP.buildPkg:exec stderr ', stderr);
	}

	// compressing.tar.compressDir('builtPkg', 'builtPkg/cif_plugin.tar')
	const handleError = (err) => {
		if (err) {
			console.log('CIF.CP.buildPkg:exec handleError ', err);
		}
	};

	let withAssets = false;
	// let assetsFilePath = []

	try {
		fs.accessSync('builtPkg/cif_assets', fs.constants.R_OK | fs.constants.W_OK);
		console.log('CIF.CP.buildPkg:exec 发现静态资源');
		withAssets = true;
		// assetsFilePath = fs.readdirSync("builtPkg/img");
	} catch (err) {
		console.log('CIF.CP.buildPkg:exec 未发现静态资源');
	}

	//把data对象转换为json格式字符串
	const content = JSON.stringify({
		name: config.name,
		version: config.version,
		type: config.type,
		withAssets: withAssets
	});
	//指定创建目录及文件名称，__dirname为执行当前js文件的目录 ../../../builtPkg/baseinfo.json
	const file = path.join(process.cwd(), 'builtPkg/baseinfo.json');

	//写入文件
	fs.writeFile(file, content, 'utf-8', function (err) {
		if (err) {
			console.log('CIF.CP.buildPkg:exec 配置文件创建失败 ', err);
		}
		console.log('CIF.CP.buildPkg:exec 配置文件创建成功，地址：', file);

		// 检查文件是否存在于当前目录中。
		fs.access(file, fs.constants.F_OK, (err) => {
			console.log(`${file} ${err ? '不存在' : '存在'}`);
		});

		const tarStream = new compressing.zip.Stream();
		// file
		tarStream.addEntry(`builtPkg/${pkg}.css`);
		tarStream.addEntry(`builtPkg/${pkg}.common.js`);
		tarStream.addEntry(`builtPkg/${pkg}.umd.js`);
		tarStream.addEntry(`builtPkg/${pkg}.umd.js`);
		tarStream.addEntry('builtPkg/baseinfo.json');

		if (withAssets) {
			tarStream.addEntry('builtPkg/cif_assets');
		}

		const destStream = fs.createWriteStream(`builtPkg/${pkg}.zip`);
		pipeline(tarStream, destStream, handleError);
	});
});
